package org.nowcoder.leetcode.twoPointers;

/**
 * Title  : 19. Remove Nth Node From End of List
 * Source : https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-13
 */

public class LeetCode_19 {
    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        //处理特殊情况
        if (head.next == null) {
            return null;
        }
        //难点： 如何处理倒数n
        ListNode p = head;
        int count = 0;
        while (p != null) {
            count++;
            p = p.next;
        }
        n = count - n;
        p = head;
        count = 1;
        while (p != null) {
            if (n == 0) {
                head = p.next;
                break;
            } else if (count == n) {
                p.next = p.next.next;
                break;
            }
            count++;
            p = p.next;
        }
        return head;
    }
}
